package net.ipinglun.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import net.ipinglun.R;
import net.ipinglun.activitys.NewsDetailActivity;
import net.ipinglun.adapters.NewsWaterFallListViewAdapter;
import net.ipinglun.http.GetNewsListResponseHandler;
import net.ipinglun.models.NewsBean;
import net.ipinglun.models.NewsListBean;
import net.ipinglun.presenters.NewsPresenter;
import net.ipinglun.utils.Tools;
import net.ipinglun.waterfall.MultiColumnListView;
import net.ipinglun.waterfall.PLA_AbsListView;
import net.ipinglun.waterfall.PLA_AdapterView;

public class NewsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, PLA_AbsListView.OnScrollListener, PLA_AdapterView.OnItemClickListener{


    private int mChannelId;
    private Context mContext;
    private Activity mActivity;
    private Boolean mFristLoad = true;
    private NewsPresenter mPresenter;
    private int mLastItem = 0;
    private int mPager = 0;
    private Boolean mLoading = false;
    private String mNewsListUrl;


    private SwipeRefreshLayout mSwipeLayout;
    private MultiColumnListView mWaterFallList;
    private NewsWaterFallListViewAdapter mListAdapter;
    private RelativeLayout mFooter;


    public static NewsFragment newInstance(int channelId) {

        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putInt("channelId", channelId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Bundle arg = getArguments();
        mChannelId = arg.getInt("channelId");
        mContext = getActivity();
        mActivity = getActivity();


        if (mChannelId == 0) {
            mNewsListUrl = "http://api.wallstreetcn.com/v2/posts?type=news&page=";
        } else {
            mNewsListUrl = "http://api.wallstreetcn.com/v2/posts?cid=11&page=";
        }


        return inflater.inflate(R.layout.fragment_news, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        //mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()));

        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorScheme(R.color.main_color, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_blue_light);

        mWaterFallList =  (MultiColumnListView) view.findViewById(R.id.waterfall_list);
        mWaterFallList.setSmoothScrollbarEnabled(true);
        mWaterFallList.setOnScrollListener(this);
        mWaterFallList.setOnItemClickListener(this);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mListAdapter = new NewsWaterFallListViewAdapter(mContext, mChannelId);

        // 自动加载footer
        mFooter = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.waterfall_footer, null);
        mWaterFallList.addFooterView(mFooter);
        mFooter.setVisibility(View.INVISIBLE);

        mWaterFallList.setAdapter(mListAdapter);


        mPresenter = new NewsPresenter(mContext);
        mPresenter.setChannelId(mChannelId);

        // 对用户可见再加载
        if (getUserVisibleHint())
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    onRefresh();
                }
            }, 100);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (!isVisibleToUser) return;

        // 可见时操作
        if (mFristLoad && mSwipeLayout != null) {
            onRefresh();
            return;
        }

        // 防止滚到超过第二页还要加载
        if (mContext != null && Tools.isNetworkConnected(mContext) && !mFristLoad && mListAdapter.getCount() > 0 && mListAdapter.getCount() <= 30) {
            //checkDataExpireStatus();
        }
    }

    public void checkDataExpireStatus() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                onRefresh();
            }
        }, 200);
    }


    public void onRefresh() {

        mFristLoad = false;

        if (mLoading) {
            return;
        }

        mPager = 0;


        if (!mSwipeLayout.isRefreshing())
            mSwipeLayout.setRefreshing(true);

        if (mSwipeLayout.isRefreshing())
            getNewsList(mPager);
    }


    public void getNewsList(int pager) {

        mPresenter.getNewsList(pager, new GetNewsListResponseHandler() {
                            @Override
                            public void onStart() {
                                mLoading = true;
                            }

                            @Override
                            public void onSuccess(NewsListBean newsList) {

                                mFooter.setVisibility(View.INVISIBLE);

                                mListAdapter.addItems(newsList.newsList, mPager);
                                mListAdapter.notifyDataSetChanged();

                                mPager++;
                            }

                            @Override
                            public void onFailure() {
                            }

                            @Override
                            public void onFinish() {

                                mLoading = false;
                                if (mSwipeLayout.isRefreshing()) {
                                    mSwipeLayout.setRefreshing(false);
                                }
                            }


                            @Override
                            public void onLoadCache(NewsListBean newsList) {

                            }

        });
    }

    @Override
    public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {
        //System.out.println("lastItem: " + mLastItem + "  mListAdapter.getCount(): " + mListAdapter.getCount());

        if (mLoading) {
            return;
        }

        if (mLastItem == mListAdapter.getCount() + mWaterFallList.getHeaderViewsCount() + mWaterFallList.getFooterViewsCount()) {
            mFooter.setVisibility(View.VISIBLE);
            getNewsList(mPager);
        }
    }

    @Override
    public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        mLastItem = firstVisibleItem + visibleItemCount;

    }

    @Override
    public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {

        int index = position - mWaterFallList.getHeaderViewsCount();
        NewsBean news = mListAdapter.getItems().get(index);

        Intent intent = new Intent(mContext, NewsDetailActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("id", news.id);
        intent.putExtras(bundle);

        startActivity(intent);

    }

}
